package com.easthome.interceptor;

import com.easthome.common.RespResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * session ,,,
 * 用户如果登录了，就放行
 * 如果没登录 ，去重定向到登录页面
 * @author cxiaoy
 * @Date 2022/10/13 15:44
 */
public class Interceptor01 implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(request.getRequestURI());
        System.out.println("进入controller之前的操作.....");

        //先判断session 里的user，如果不为空，就放行；如果为空，又判断又判断 你是不是img..login....register..
        Object user = request.getSession().getAttribute("user");
        if(user==null){
            //判断 一下是否是ajax请求，
            if(
                    (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest"))
                || (request.getHeader("axiosReq")!=null)
            ){
                ObjectMapper mapper = new ObjectMapper();
                RespResult result = new RespResult("请先登录", "1004", null);
                String resultJsonStr = mapper.writeValueAsString(result);
                response.getWriter().write(resultJsonStr);
            }else{
                response.sendRedirect(request.getContextPath() + "/static/jsp/login.jsp");
            }

            return false;
        }
        return true;//代表放行。
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("controller结束后，如果没有异常，就会走的操作...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("controller有没有异常，都会最终走的操作....");
    }
}
